package pers.qianyu.month_202012.date_20201202;

import java.util.*;

/**
 * 归并排序
 *
 * @author mizzle rain
 * @date 2020-12-02 21:52
 */
public class MergeSort {
    public void sort(int[] arr) {
        int[] temp = new int[arr.length];
        solve(arr, 0, arr.length - 1, temp);
    }

    private void solve(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }
        // 分
        int mid = left + ((right - left) >> 1);
        solve(arr, left, mid, temp);
        solve(arr, mid + 1, right, temp);
        // 合并数组
        int p1 = left, p2 = mid + 1, k = 0;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] < arr[p2]) {
                temp[k++] = arr[p1++];
            } else {
                temp[k++] = arr[p2++];
            }
        }
        while (p1 <= mid) {
            temp[k++] = arr[p1++];
        }
        while (p2 <= right) {
            temp[k++] = arr[p2++];
        }
        // 将辅助数组中的数写回原数组
        k = 0;
        for (int i = left; i <= right; i++) {
            arr[i] = temp[k++];
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 2, 5, 1, 2, 7, 3, 9, 9, 8, -1};
        new MergeSort().sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
